package org.jeecg.modules.inspect.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.inspect.entity.InsClassesCheckInterval;
import org.jeecg.modules.inspect.entity.InsClassesCheckIntervalTime;
import org.jeecg.modules.inspect.entity.InsClassesCheckIntervalUser;
import org.jeecg.modules.inspect.service.IInsClassesCheckIntervalService;
import org.jeecg.modules.inspect.service.IInsClassesCheckIntervalTimeService;
import org.jeecg.modules.inspect.service.IInsClassesCheckIntervalUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: ins_classes_check_interval
 * @Author: jeecg-boot
 * @Date:   2024-04-11
 * @Version: V1.0
 */
@Api(tags="ins_classes_check_interval")
@RestController
@RequestMapping("/inspect/insClassesCheckInterval")
@Slf4j
public class InsClassesCheckIntervalController extends JeecgController<InsClassesCheckInterval, IInsClassesCheckIntervalService> {

	@Autowired
	private IInsClassesCheckIntervalService insClassesCheckIntervalService;

	@Autowired
	private IInsClassesCheckIntervalUserService insClassesCheckIntervalUserService;

	@Autowired
	private IInsClassesCheckIntervalTimeService insClassesCheckIntervalTimeService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param insClassesCheckInterval
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "ins_classes_check_interval-分页列表查询")
	@ApiOperation(value="ins_classes_check_interval-分页列表查询", notes="ins_classes_check_interval-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<InsClassesCheckInterval>> queryPageList(InsClassesCheckInterval insClassesCheckInterval,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<InsClassesCheckInterval> queryWrapper = QueryGenerator.initQueryWrapper(insClassesCheckInterval, req.getParameterMap());
		Page<InsClassesCheckInterval> page = new Page<InsClassesCheckInterval>(pageNo, pageSize);
		IPage<InsClassesCheckInterval> pageList = insClassesCheckIntervalService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
     *   添加
     * @param insClassesCheckInterval
     * @return
     */
    @AutoLog(value = "ins_classes_check_interval-添加")
    @ApiOperation(value="ins_classes_check_interval-添加", notes="ins_classes_check_interval-添加")
    //@RequiresPermissions("org.jeecg.modules:ins_classes_check_interval:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody InsClassesCheckInterval insClassesCheckInterval) {
        insClassesCheckIntervalService.save(insClassesCheckInterval);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     * @param insClassesCheckInterval
     * @return
     */
    @AutoLog(value = "ins_classes_check_interval-编辑")
    @ApiOperation(value="ins_classes_check_interval-编辑", notes="ins_classes_check_interval-编辑")
    //@RequiresPermissions("org.jeecg.modules:ins_classes_check_interval:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody InsClassesCheckInterval insClassesCheckInterval) {
        insClassesCheckIntervalService.updateById(insClassesCheckInterval);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "ins_classes_check_interval-通过id删除")
    @ApiOperation(value="ins_classes_check_interval-通过id删除", notes="ins_classes_check_interval-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:ins_classes_check_interval:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        insClassesCheckIntervalService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "ins_classes_check_interval-批量删除")
    @ApiOperation(value="ins_classes_check_interval-批量删除", notes="ins_classes_check_interval-批量删除")
    //@RequiresPermissions("org.jeecg.modules:ins_classes_check_interval:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.insClassesCheckIntervalService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    //@RequiresPermissions("org.jeecg.modules:ins_classes_check_interval:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InsClassesCheckInterval insClassesCheckInterval) {
        return super.exportXls(request, insClassesCheckInterval, InsClassesCheckInterval.class, "ins_classes_check_interval");
    }

    /**
     * 导入
     * @return
     */
    //@RequiresPermissions("org.jeecg.modules:ins_classes_check_interval:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, InsClassesCheckInterval.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-用户-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "用户-通过主表ID查询")
	@ApiOperation(value="用户-通过主表ID查询", notes="用户-通过主表ID查询")
	@GetMapping(value = "/listInsClassesCheckIntervalUserByMainId")
    public Result<IPage<InsClassesCheckIntervalUser>> listInsClassesCheckIntervalUserByMainId(InsClassesCheckIntervalUser insClassesCheckIntervalUser,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<InsClassesCheckIntervalUser> queryWrapper = QueryGenerator.initQueryWrapper(insClassesCheckIntervalUser, req.getParameterMap());
        Page<InsClassesCheckIntervalUser> page = new Page<InsClassesCheckIntervalUser>(pageNo, pageSize);
        IPage<InsClassesCheckIntervalUser> pageList = insClassesCheckIntervalUserService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param insClassesCheckIntervalUser
	 * @return
	 */
	@AutoLog(value = "用户-添加")
	@ApiOperation(value="用户-添加", notes="用户-添加")
	@PostMapping(value = "/addInsClassesCheckIntervalUser")
	public Result<String> addInsClassesCheckIntervalUser(@RequestBody InsClassesCheckIntervalUser insClassesCheckIntervalUser) {
		insClassesCheckIntervalUserService.save(insClassesCheckIntervalUser);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param insClassesCheckIntervalUser
	 * @return
	 */
	@AutoLog(value = "用户-编辑")
	@ApiOperation(value="用户-编辑", notes="用户-编辑")
	@RequestMapping(value = "/editInsClassesCheckIntervalUser", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editInsClassesCheckIntervalUser(@RequestBody InsClassesCheckIntervalUser insClassesCheckIntervalUser) {
		insClassesCheckIntervalUserService.updateById(insClassesCheckIntervalUser);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "用户-通过id删除")
	@ApiOperation(value="用户-通过id删除", notes="用户-通过id删除")
	@DeleteMapping(value = "/deleteInsClassesCheckIntervalUser")
	public Result<String> deleteInsClassesCheckIntervalUser(@RequestParam(name="id",required=true) String id) {
		insClassesCheckIntervalUserService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "用户-批量删除")
	@ApiOperation(value="用户-批量删除", notes="用户-批量删除")
	@DeleteMapping(value = "/deleteBatchInsClassesCheckIntervalUser")
	public Result<String> deleteBatchInsClassesCheckIntervalUser(@RequestParam(name="ids",required=true) String ids) {
	    this.insClassesCheckIntervalUserService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportInsClassesCheckIntervalUser")
    public ModelAndView exportInsClassesCheckIntervalUser(HttpServletRequest request, InsClassesCheckIntervalUser insClassesCheckIntervalUser) {
		 // Step.1 组装查询条件
		 QueryWrapper<InsClassesCheckIntervalUser> queryWrapper = QueryGenerator.initQueryWrapper(insClassesCheckIntervalUser, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<InsClassesCheckIntervalUser> pageList = insClassesCheckIntervalUserService.list(queryWrapper);
		 List<InsClassesCheckIntervalUser> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "用户");
		 mv.addObject(NormalExcelConstants.CLASS, InsClassesCheckIntervalUser.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户报表", "导出人:" + sysUser.getRealname(), "用户"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importInsClassesCheckIntervalUser/{mainId}")
    public Result<?> importInsClassesCheckIntervalUser(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<InsClassesCheckIntervalUser> list = ExcelImportUtil.importExcel(file.getInputStream(), InsClassesCheckIntervalUser.class, params);
				 for (InsClassesCheckIntervalUser temp : list) {
                    temp.setIntervalId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 insClassesCheckIntervalUserService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-用户-end----------------------------------------------*/

    /*--------------------------------子表处理-值班打卡时间-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "值班打卡时间-通过主表ID查询")
	@ApiOperation(value="值班打卡时间-通过主表ID查询", notes="值班打卡时间-通过主表ID查询")
	@GetMapping(value = "/listInsClassesCheckIntervalTimeByMainId")
    public Result<IPage<InsClassesCheckIntervalTime>> listInsClassesCheckIntervalTimeByMainId(InsClassesCheckIntervalTime insClassesCheckIntervalTime,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<InsClassesCheckIntervalTime> queryWrapper = QueryGenerator.initQueryWrapper(insClassesCheckIntervalTime, req.getParameterMap());
        Page<InsClassesCheckIntervalTime> page = new Page<InsClassesCheckIntervalTime>(pageNo, pageSize);
        IPage<InsClassesCheckIntervalTime> pageList = insClassesCheckIntervalTimeService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param insClassesCheckIntervalTime
	 * @return
	 */
	@AutoLog(value = "值班打卡时间-添加")
	@ApiOperation(value="值班打卡时间-添加", notes="值班打卡时间-添加")
	@PostMapping(value = "/addInsClassesCheckIntervalTime")
	public Result<String> addInsClassesCheckIntervalTime(@RequestBody InsClassesCheckIntervalTime insClassesCheckIntervalTime) {
		insClassesCheckIntervalTimeService.save(insClassesCheckIntervalTime);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param insClassesCheckIntervalTime
	 * @return
	 */
	@AutoLog(value = "值班打卡时间-编辑")
	@ApiOperation(value="值班打卡时间-编辑", notes="值班打卡时间-编辑")
	@RequestMapping(value = "/editInsClassesCheckIntervalTime", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editInsClassesCheckIntervalTime(@RequestBody InsClassesCheckIntervalTime insClassesCheckIntervalTime) {
		insClassesCheckIntervalTimeService.updateById(insClassesCheckIntervalTime);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "值班打卡时间-通过id删除")
	@ApiOperation(value="值班打卡时间-通过id删除", notes="值班打卡时间-通过id删除")
	@DeleteMapping(value = "/deleteInsClassesCheckIntervalTime")
	public Result<String> deleteInsClassesCheckIntervalTime(@RequestParam(name="id",required=true) String id) {
		insClassesCheckIntervalTimeService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "值班打卡时间-批量删除")
	@ApiOperation(value="值班打卡时间-批量删除", notes="值班打卡时间-批量删除")
	@DeleteMapping(value = "/deleteBatchInsClassesCheckIntervalTime")
	public Result<String> deleteBatchInsClassesCheckIntervalTime(@RequestParam(name="ids",required=true) String ids) {
	    this.insClassesCheckIntervalTimeService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportInsClassesCheckIntervalTime")
    public ModelAndView exportInsClassesCheckIntervalTime(HttpServletRequest request, InsClassesCheckIntervalTime insClassesCheckIntervalTime) {
		 // Step.1 组装查询条件
		 QueryWrapper<InsClassesCheckIntervalTime> queryWrapper = QueryGenerator.initQueryWrapper(insClassesCheckIntervalTime, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<InsClassesCheckIntervalTime> pageList = insClassesCheckIntervalTimeService.list(queryWrapper);
		 List<InsClassesCheckIntervalTime> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "值班打卡时间");
		 mv.addObject(NormalExcelConstants.CLASS, InsClassesCheckIntervalTime.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("值班打卡时间报表", "导出人:" + sysUser.getRealname(), "值班打卡时间"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importInsClassesCheckIntervalTime/{mainId}")
    public Result<?> importInsClassesCheckIntervalTime(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<InsClassesCheckIntervalTime> list = ExcelImportUtil.importExcel(file.getInputStream(), InsClassesCheckIntervalTime.class, params);
				 for (InsClassesCheckIntervalTime temp : list) {
                    temp.setIntervalId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 insClassesCheckIntervalTimeService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-值班打卡时间-end----------------------------------------------*/


	 @Autowired
	 private JdbcTemplate jdbcTemplate;
	 /**
	  * 根据用户名称（编号）查询打卡区间
	  * @return
	  */
	 @GetMapping(value = "/queryIntervalByUserName")
	 public List<Map<String, Object>> queryIntervalByUserName(String userName) {
		 String sql =
				 " select u.user_id,t.class_time_pre,t.class_time_end from ins_classes_check_interval m  " +
				 " inner join ins_classes_check_interval_user u on u.interval_id=m.id " +
				 " inner join ins_classes_check_interval_time t on t.interval_id=m.id " +
				 " where u.user_id='"+userName+"'";
		 List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
		 return CollectionUtils.isNotEmpty(result)?result:new ArrayList<>();
	 }
}
